package com.zlm.udpThread;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

/**
 * @Author: 郑
 * UDP发送数据线程类
 */
public class UdpSend implements Runnable{

    boolean flag = true;
    DatagramSocket socket = null;
    BufferedReader bufferedReader = null;

    private int fromPort;
    private int toPort;
    private String toIp;

    public UdpSend(int fromPort, int toPort, String toIp) {
        this.fromPort = fromPort;
        this.toPort = toPort;
        this.toIp = toIp;
        try {
            socket = new DatagramSocket(fromPort);
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {

        try {
            while (flag) {
                String msg = bufferedReader.readLine();
                DatagramPacket dataPacket = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, new InetSocketAddress(toIp,toPort));
                socket.send(dataPacket);
                if(msg.equals("bye")){
                    flag = false;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        socket.close();
    }
}
